/*
 ####        # 
 #           #
 ## ### #  # #
 #  #-# #\ # #
 #  # # # \# ####
 Author: Felipe de Andrade Neves Lavratti

 Copyright: There are no restrictions. Use as you want.	  
*/

/*
	LPC 2478
	+ TFT DISPLAY
	+ TOUCH PANNEL
	+ SWIM
	+ SDRAM

	Get more at: selivre.wordpress.com
*/
#include "timer.h"

void T0Init(int ms)
{
	T0TCR =	0;		 /* Desabilita T0 */
  	/* Prescaler para incrementar o T0TC 1000 vezes por segundo */
	T0PR = (CPU_CLOCK_HZ/4000)*ms - 1;
	T0TCR =	2;		/* Inicializa T0 */
}

void T0Stop()
{
	T0TCR = 0;
}
void T0Reset()
{
	T0TCR = 2;
}
void T0Start()
{
	T0TCR = 1;
}

void delayMs(UNS_32 delayInMs)
{
	/*
	* setup timer #1 for delay
	*/
	T2TCR = 0x02;		/* reset timer */
	T2PR  = (CPU_CLOCK_HZ/4000);		/* set prescaler to zero */
	T2MR0 = delayInMs -1;
	T2IR  = 0xff;		/* reset all interrrupts */
	T2MCR = 0x04;		/* stop timer on match */
	T2TCR = 0x01;		/* start timer */

	/* wait until delay time has elapsed */
	while (T2TCR & 0x01);
  return;
}

void delayUs(UNS_32 delayInUs)
{
	/*
	* setup timer #1 for delay
	*/
	T2TCR = 0x02;		/* reset timer */
	T2PR  = 0x00;		/* set prescaler to zero */
	T2MR0 = delayInUs * (CPU_CLOCK_HZ/4000000 -1);
	T2IR  = 0xff;		/* reset all interrrupts */
	T2MCR = 0x04;		/* stop timer on match */
	T2TCR = 0x01;		/* start timer */

	/* wait until delay time has elapsed */
	while (T2TCR & 0x01);
  return;
}

int timeoutMs(UNS_32 delayInMs, UNS_32 condition)
{
	switch(condition)
	{
	case START:
		T1TCR = 0x02;		/* reset timer */
		T1PR  = 0x00;		/* set prescaler to zero */
		T1MR0 = delayInMs * (CPU_CLOCK_HZ/4000 -1);
		T1IR  = 0xff;		/* reset all interrrupts */
		T1MCR = 0x04;		/* stop timer on match */
		T1TCR = 0x01;		/* start timer */
		break;

	case CHECK_IF_MATCH:
		if (T1TCR&0x01) return NOT_MATCH;
		else return MATCH;

	}

	return 1;
}
